在此要來修正console報的錯誤
Warning: Each child in a list should have a unique "key" prop
這是因為
React element 在render時候若不用 key
則React 就會報以下error message
~\ClientApp\src\components\Home.js
會有錯誤的程式碼
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import Rating from './Rating';
export class Home extends Component {
static displayName = Home.name;
constructor(props) {
super(props);
this.state = {
products: [
{ title: "some product", description: "interesting", id: 1, averageRating: 3 },
{ title: "another product", description: "more", id: 2, averageRating: 4 }
]
};
}
render() {
return (
<div className="row">
{this.state.products.map(product =>
<div className="col-4">
<div className="card product-card">
<div className="card-body">
<h5 className="card-title">{product.title}</h5>
<p className="card-text">{product.description}</p>
<Link to={`/product/${product.id}`}>Detail</Link>
<p>rate:<Rating rating={product.averageRating} /></p>
</div>
</div>
</div>
)
}
</div>
);
}
}
修正好的程式碼
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import Rating from './Rating';
export class Home extends Component {
static displayName = Home.name;
constructor(props) {
super(props);
this.state = {
products: [
{ title: "some product", description: "interesting", id: 1, averageRating: 3 },
{ title: "another product", description: "more", id: 2, averageRating: 4 }
]
};
}
render() {
return (
<div className="row">
{this.state.products.map(product =>
<div key={product.id} className="col-4">
<div className="card product-card">
<div className="card-body">
<h5 className="card-title">{product.title}</h5>
<p className="card-text">{product.description}</p>
<Link to={`/product/${product.id}`}>Detail</Link>
<p>rate:<Rating rating={product.averageRating} /></p>
</div>
</div>
</div>
)
}
</div>
);
}
}